package com.papercutting.platform.util;

import com.papercutting.platform.dto.request.CultureRequest;
import com.papercutting.platform.dto.request.NewsRequest;
import com.papercutting.platform.dto.request.UserCreateRequest;
import com.papercutting.platform.dto.request.UserUpdateRequest;
import com.papercutting.platform.dto.response.CultureResponse;
import com.papercutting.platform.dto.response.NewsResponse;
import com.papercutting.platform.dto.response.UserResponse;
import com.papercutting.platform.entity.Culture;
import com.papercutting.platform.entity.News;
import com.papercutting.platform.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 实体转换工具类
 */
public class EntityConverter {
    
    /**
     * UserCreateRequest -> User
     */
    public static User toUser(UserCreateRequest request) {
        if (request == null) {
            return null;
        }
        
        User user = new User();
        BeanUtils.copyProperties(request, user);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setDeleted(false);
        
        // 密码加密
        if (StringUtils.hasText(request.getPassword())) {
            user.setPassword(PasswordUtil.encode(request.getPassword()));
        } else {
            // 如果没有提供密码，生成默认密码 "123456"
            user.setPassword(PasswordUtil.encode("123456"));
        }
        
        return user;
    }
    
    /**
     * UserUpdateRequest -> User (只更新非空字段)
     */
    public static void updateUser(User user, UserUpdateRequest request) {
        if (request == null || user == null) {
            return;
        }
        
        if (StringUtils.hasText(request.getNickname())) {
            user.setNickname(request.getNickname());
        }
        if (StringUtils.hasText(request.getPhone())) {
            user.setPhone(request.getPhone());
        }
        if (StringUtils.hasText(request.getEmail())) {
            user.setEmail(request.getEmail());
        }
        if (StringUtils.hasText(request.getAvatarUrl())) {
            user.setAvatarUrl(request.getAvatarUrl());
        }
        if (request.getGender() != null) {
            user.setGender(request.getGender());
        }
        if (StringUtils.hasText(request.getCountry())) {
            user.setCountry(request.getCountry());
        }
        if (StringUtils.hasText(request.getProvince())) {
            user.setProvince(request.getProvince());
        }
        if (StringUtils.hasText(request.getCity())) {
            user.setCity(request.getCity());
        }
        if (StringUtils.hasText(request.getLanguage())) {
            user.setLanguage(request.getLanguage());
        }
        if (request.getStatus() != null) {
            user.setStatus(request.getStatus());
        }
        if (request.getUserType() != null) {
            user.setUserType(request.getUserType());
        }
        if (StringUtils.hasText(request.getRemark())) {
            user.setRemark(request.getRemark());
        }
        
        user.setUpdateTime(LocalDateTime.now());
    }
    
    /**
     * User -> UserResponse
     */
    public static UserResponse toUserResponse(User user) {
        if (user == null) {
            return null;
        }
        
        UserResponse response = new UserResponse();
        BeanUtils.copyProperties(user, response);
        
        // 脱敏处理
        if (StringUtils.hasText(user.getPhone())) {
            response.setPhone(maskPhone(user.getPhone()));
        }
        if (StringUtils.hasText(user.getEmail())) {
            response.setEmail(maskEmail(user.getEmail()));
        }
        
        return response;
    }
    
    /**
     * List<User> -> List<UserResponse>
     */
    public static List<UserResponse> toUserResponseList(List<User> users) {
        if (users == null) {
            return null;
        }
        return users.stream()
                .map(EntityConverter::toUserResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 手机号脱敏
     */
    private static String maskPhone(String phone) {
        if (phone == null || phone.length() < 11) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
    
    /**
     * 邮箱脱敏
     */
    private static String maskEmail(String email) {
        if (email == null || !email.contains("@")) {
            return email;
        }
        String[] parts = email.split("@");
        if (parts[0].length() <= 2) {
            return email;
        }
        return parts[0].substring(0, 2) + "***@" + parts[1];
    }

    // ==================== Culture 相关转换方法 ====================

    /**
     * CultureRequest -> Culture
     */
    public static Culture toCulture(CultureRequest request) {
        if (request == null) {
            return null;
        }

        Culture culture = new Culture();
        BeanUtils.copyProperties(request, culture);

        return culture;
    }

    /**
     * CultureRequest -> Culture (只更新非空字段)
     */
    public static void updateCulture(Culture culture, CultureRequest request) {
        if (request == null || culture == null) {
            return;
        }

        if (StringUtils.hasText(request.getTitle())) {
            culture.setTitle(request.getTitle());
        }
        if (StringUtils.hasText(request.getSubtitle())) {
            culture.setSubtitle(request.getSubtitle());
        }
        if (StringUtils.hasText(request.getCoverImage())) {
            culture.setCoverImage(request.getCoverImage());
        }
        if (StringUtils.hasText(request.getSummary())) {
            culture.setSummary(request.getSummary());
        }
        if (StringUtils.hasText(request.getContent())) {
            culture.setContent(request.getContent());
        }
        if (request.getCategory() != null) {
            culture.setCategory(request.getCategory());
        }
        if (StringUtils.hasText(request.getTags())) {
            culture.setTags(request.getTags());
        }
        if (request.getSortOrder() != null) {
            culture.setSortOrder(request.getSortOrder());
        }
        if (request.getStatus() != null) {
            culture.setStatus(request.getStatus());
        }
        if (request.getIsRecommend() != null) {
            culture.setIsRecommend(request.getIsRecommend());
        }
        if (request.getIsTop() != null) {
            culture.setIsTop(request.getIsTop());
        }
    }

    /**
     * Culture -> CultureResponse
     */
    public static CultureResponse toCultureResponse(Culture culture) {
        if (culture == null) {
            return null;
        }

        CultureResponse response = new CultureResponse();
        BeanUtils.copyProperties(culture, response);

        // 设置分类和状态的文本描述
        response.setCategory(culture.getCategory());
        response.setStatus(culture.getStatus());

        return response;
    }

    /**
     * Culture -> CultureResponse 列表转换
     */
    public static List<CultureResponse> toCultureResponseList(List<Culture> cultures) {
        if (cultures == null) {
            return null;
        }

        return cultures.stream()
                .map(EntityConverter::toCultureResponse)
                .collect(Collectors.toList());
    }

    // ==================== News 相关转换方法 ====================

    /**
     * NewsRequest -> News
     */
    public static News toNews(NewsRequest request) {
        if (request == null) {
            return null;
        }

        News news = new News();
        BeanUtils.copyProperties(request, news);
        news.setCreateTime(LocalDateTime.now());
        news.setUpdateTime(LocalDateTime.now());
        news.setDeleted(false);

        // 设置默认值
        if (news.getViewCount() == null) news.setViewCount(0);
        if (news.getLikeCount() == null) news.setLikeCount(0);
        if (news.getShareCount() == null) news.setShareCount(0);
        if (news.getSortOrder() == null) news.setSortOrder(0);
        if (news.getIsRecommend() == null) news.setIsRecommend(false);
        if (news.getIsTop() == null) news.setIsTop(false);

        return news;
    }

    /**
     * NewsRequest -> News (只更新非空字段)
     */
    public static void updateNews(News news, NewsRequest request) {
        if (request == null || news == null) {
            return;
        }

        if (StringUtils.hasText(request.getTitle())) {
            news.setTitle(request.getTitle());
        }
        if (StringUtils.hasText(request.getSubtitle())) {
            news.setSubtitle(request.getSubtitle());
        }
        if (StringUtils.hasText(request.getCoverImage())) {
            news.setCoverImage(request.getCoverImage());
        }
        if (StringUtils.hasText(request.getSummary())) {
            news.setSummary(request.getSummary());
        }
        if (StringUtils.hasText(request.getContent())) {
            news.setContent(request.getContent());
        }
        if (request.getType() != null) {
            news.setType(request.getType());
        }
        if (StringUtils.hasText(request.getTags())) {
            news.setTags(request.getTags());
        }
        if (StringUtils.hasText(request.getAuthor())) {
            news.setAuthor(request.getAuthor());
        }
        if (StringUtils.hasText(request.getSource())) {
            news.setSource(request.getSource());
        }
        if (request.getPublishTime() != null) {
            news.setPublishTime(request.getPublishTime());
        }
        if (request.getEventStartTime() != null) {
            news.setEventStartTime(request.getEventStartTime());
        }
        if (request.getEventEndTime() != null) {
            news.setEventEndTime(request.getEventEndTime());
        }
        if (StringUtils.hasText(request.getEventLocation())) {
            news.setEventLocation(request.getEventLocation());
        }
        if (request.getSortOrder() != null) {
            news.setSortOrder(request.getSortOrder());
        }
        if (request.getStatus() != null) {
            news.setStatus(request.getStatus());
        }
        if (request.getIsRecommend() != null) {
            news.setIsRecommend(request.getIsRecommend());
        }
        if (request.getIsTop() != null) {
            news.setIsTop(request.getIsTop());
        }

        news.setUpdateTime(LocalDateTime.now());
    }

    /**
     * News -> NewsResponse
     */
    public static NewsResponse toNewsResponse(News news) {
        if (news == null) {
            return null;
        }

        NewsResponse response = new NewsResponse();
        BeanUtils.copyProperties(news, response);

        // 设置类型和状态的文本描述
        response.setType(news.getType());
        response.setStatus(news.getStatus());

        return response;
    }

    /**
     * News -> NewsResponse 列表转换
     */
    public static List<NewsResponse> toNewsResponseList(List<News> newsList) {
        if (newsList == null) {
            return null;
        }

        return newsList.stream()
                .map(EntityConverter::toNewsResponse)
                .collect(Collectors.toList());
    }
}